package com.satan.config.security;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.satan.entity.SysMenu;
import com.satan.entity.SysRole;
import com.satan.entity.SysUser;
import com.satan.entity.response.ResultEntity;
import com.satan.service.SysMenuService;
import com.satan.service.SysRoleService;
import com.satan.service.SysUserService;
import com.satan.util.JwtUtil;
import com.satan.util.WebUtil;
import com.satan.vo.SysUserVo;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Component
@Slf4j
@RequiredArgsConstructor
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    private final SysUserService sysUserService;

    private final SysRoleService sysRoleService;
    private final SysMenuService sysMenuService;


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) throws IOException, ServletException, IOException {
        AuthenticationSuccessHandler.super.onAuthenticationSuccess(request, response, chain, authentication);
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = response.getOutputStream();
        String userName = authentication.getName();
        log.info("登录成功用户名:{}", userName);
        String token = JwtUtil.genJwtToken(userName);
        //获取当前用户信息
        SysUser currentUser = sysUserService.getUserByName(userName);
        // 根据用户id获取所有的角色信息
        List<SysRole> roleList = sysRoleService.list(new QueryWrapper<SysRole>().inSql("id", "SELECT role_id FROM sys_user_role WHERE user_id=" + currentUser.getId()));


        log.info("用户角色:{}", roleList);
        // 遍历所有的角色，获取所有菜单权限 而且不重复
        Set<SysMenu> menuSet = new HashSet<>();
        for (SysRole sysRole : roleList) {
            List<SysMenu> sysMenuList = sysMenuService.list(new QueryWrapper<SysMenu>().inSql("id", "SELECT menu_id FROM sys_role_menu WHERE role_id=" + sysRole.getId()));
            for (SysMenu sysMenu : sysMenuList) {
                menuSet.add(sysMenu);
            }
        }
        SysUserVo sysUserVo = new SysUserVo();
        BeanUtils.copyProperties(currentUser, sysUserVo);
        sysUserVo.setRoles(roleList.stream().map(SysRole::getName).collect(Collectors.joining(",")));
        List<SysMenu> sysMenuList = new ArrayList<>(menuSet);
        //排序
        sysMenuList.sort(Comparator.comparing(SysMenu::getOrderNum));
        log.info("用户菜单:{}", sysMenuList);
        //转菜单树
        List<SysMenu> menuList = sysMenuService.buildTreeMenu(sysMenuList);
        System.out.println("menuList = " + menuList);
        Map map = new HashMap();
        map.put("token", token);
        map.put("currentUser", sysUserVo);
        map.put("menuList", menuList);
        String jsonString = JSON.toJSONString(ResultEntity.success(map));
        WebUtil.renderJson(response, jsonString);

    }
}
